const { get, post } = require("../../utils/request");

Page({
  data: {
    // 用户余额信息
    rechargeBalance: "0.00", // 充值余额
    giftBalance: "0.00", // 赠送余额
    totalBalance: "0.00", // 总余额

    // 充值选项
    rechargeOptions: [
      { amount: 100, gift: 10, total: 110 },
      { amount: 200, gift: 30, total: 230 },
      { amount: 500, gift: 100, total: 600 },
      { amount: 1000, gift: 300, total: 1300 },
    ],
    selectedOption: null, // 选中的充值选项

    // 自定义充值
    customAmount: "", // 自定义充值金额

    activeTab: "balance", // 默认选中的选项卡
    isLoading: false, // 是否正在加载
  },

  onLoad: function () {
    // 加载用户余额信息
    this.getUserBalance();
  },

  onShow: function () {
    // 每次页面显示时重新获取余额信息
    this.getUserBalance();
  },

  // 切换选项卡
  switchTab: function (e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab,
      selectedOption: null,
      customAmount: "",
    });
  },

  // 获取用户余额信息
  getUserBalance: function () {
    const app = getApp();
    const loginStatus = app.checkLoginStatus();

    if (!loginStatus.isLoggedIn) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });
      setTimeout(() => {
        wx.navigateTo({
          url: "/pages/registration/registration",
        });
      }, 1500);
      return;
    }

    const userInfo = loginStatus.userInfo;

    // 从用户信息中获取余额数据
    if (userInfo) {
      const rechargeBalance = parseFloat(userInfo.rechargeBalance || 0).toFixed(
        2
      );
      const giftBalance = parseFloat(userInfo.giftBalance || 0).toFixed(2);
      const totalBalance = parseFloat(
        Number(rechargeBalance) + Number(giftBalance)
      ).toFixed(2);

      this.setData({
        rechargeBalance,
        giftBalance,
        totalBalance,
      });
      return;
    }

    // 如果本地用户信息没有余额数据，则请求最新的用户信息
    this.setData({ isLoading: true });

    get(`/user/info`)
      .then((res) => {
        this.setData({ isLoading: false });

        if (res.code === 200 && res.data) {
          // 更新本地存储的用户信息
          const updatedUserInfo = res.data;
          wx.setStorageSync("userInfo", updatedUserInfo);

          // 获取余额信息
          const rechargeBalance = parseFloat(
            updatedUserInfo.rechargeBalance || 0
          ).toFixed(2);
          const giftBalance = parseFloat(
            updatedUserInfo.giftBalance || 0
          ).toFixed(2);
          const totalBalance = parseFloat(
            Number(rechargeBalance) + Number(giftBalance)
          ).toFixed(2);

          this.setData({
            rechargeBalance,
            giftBalance,
            totalBalance,
          });
        } else {
          console.error("获取用户信息失败:", res.message);
          wx.showToast({
            title: "获取余额信息失败",
            icon: "none",
          });
        }
      })
      .catch((err) => {
        this.setData({ isLoading: false });
        console.error("获取用户信息失败:", err);
        wx.showToast({
          title: "获取余额信息失败",
          icon: "none",
        });
      });
  },

  // 选择充值选项
  selectRechargeOption: function (e) {
    const index = e.currentTarget.dataset.index;
    const selectedOption = this.data.rechargeOptions[index];

    this.setData({
      selectedOption,
      customAmount: "", // 清空自定义金额
    });
  },

  // 输入自定义充值金额
  inputCustomAmount: function (e) {
    const value = e.detail.value;
    this.setData({
      customAmount: value,
      selectedOption: null, // 清空选择的充值选项
    });
  },

  // 执行充值操作
  recharge: function () {
    // 判断充值金额
    let amount = 0;
    let giftAmount = 0;

    if (this.data.selectedOption) {
      // 使用预设充值选项
      amount = this.data.selectedOption.amount;
      giftAmount = this.data.selectedOption.gift;
    } else if (this.data.customAmount) {
      // 使用自定义金额
      amount = parseFloat(this.data.customAmount);

      // 验证金额有效性
      if (isNaN(amount) || amount <= 0) {
        wx.showToast({
          title: "请输入有效金额",
          icon: "none",
        });
        return;
      }

      // 四舍五入到两位小数
      amount = Math.round(amount * 100) / 100;
    } else {
      wx.showToast({
        title: "请选择或输入充值金额",
        icon: "none",
      });
      return;
    }

    // 确认充值
    wx.showModal({
      title: "确认充值",
      content: `您将充值 ¥${amount.toFixed(2)} 元${
        giftAmount > 0 ? `，赠送 ¥${giftAmount.toFixed(2)} 元` : ""
      }`,
      confirmText: "确认充值",
      success: (res) => {
        if (res.confirm) {
          // 用户确认充值，调用支付接口
          this.processRecharge(amount, giftAmount);
        }
      },
    });
  },

  // 处理充值支付
  processRecharge: function (amount, giftAmount) {
    wx.showLoading({
      title: "处理中...",
      mask: true,
    });

    // 重新获取微信登录code以获取openid
    wx.login({
      success: (loginRes) => {
        if (loginRes.code) {
          console.log("获取到微信登录code:", loginRes.code);

          // 使用code请求后端获取openid
          post(
            "/user/wx-code-to-openid",
            { code: loginRes.code },
            {
              showLoading: false,
            }
          )
            .then((res) => {
              if (res.code === 200 && res.data && res.data.openid) {
                const openid = res.data.openid;
                console.log("成功获取openid:", openid);

                // 保存最新的openid
                wx.setStorageSync("openid", openid);

                // 创建充值订单
                this.createRechargeOrder(openid, amount, giftAmount);
              } else {
                wx.hideLoading();
                console.error("获取openid失败:", res);
                wx.showToast({
                  title: "充值初始化失败",
                  icon: "none",
                });
              }
            })
            .catch((err) => {
              wx.hideLoading();
              console.error("请求openid失败:", err);
              wx.showToast({
                title: "充值初始化失败",
                icon: "none",
              });
            });
        } else {
          wx.hideLoading();
          console.error("wx.login失败:", loginRes);
          wx.showToast({
            title: "充值初始化失败",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error("wx.login调用失败:", err);
        wx.showToast({
          title: "充值初始化失败",
          icon: "none",
        });
      },
    });
  },

  // 创建充值订单
  createRechargeOrder: function (openid, amount, giftAmount) {
    // 计算实际支付金额（单位：分）
    const payAmount = Math.floor(amount * 100);

    // 创建充值订单参数
    const queryParams = `?openid=${encodeURIComponent(
      openid
    )}&amount=${payAmount}&description=${encodeURIComponent(
      "网球场馆余额充值"
    )}`;

    // 发送请求创建支付订单
    post(`/pay/jsapi${queryParams}`, {})
      .then((res) => {
        wx.hideLoading();
        if (res.code === 200) {
          const prepayParams = res.data;
          console.log("获取到的支付参数:", prepayParams);

          // 调用微信支付
          wx.requestPayment({
            timeStamp: prepayParams.timeStamp,
            nonceStr: prepayParams.nonceStr,
            package: prepayParams.package,
            signType: prepayParams.signType,
            paySign: prepayParams.paySign,
            success: (result) => {
              console.log("充值支付成功:", result);

              // 支付成功后，调用更新余额接口
              this.updateUserBalance(amount, giftAmount);
            },
            fail: (err) => {
              console.error("充值支付失败:", err);
              if (err.errMsg === "requestPayment:fail cancel") {
                wx.showToast({
                  title: "充值已取消",
                  icon: "none",
                });
              } else {
                wx.showToast({
                  title: "充值失败，请重试",
                  icon: "none",
                });
              }
            },
          });
        } else {
          wx.showToast({
            title: res.message || "创建充值订单失败",
            icon: "none",
          });
        }
      })
      .catch((err) => {
        wx.hideLoading();
        console.error("创建充值订单失败:", err);
        wx.showToast({
          title: "创建充值订单失败",
          icon: "none",
        });
      });
  },

  // 更新用户余额
  updateUserBalance: function (amount, giftAmount) {
    wx.showLoading({
      title: "更新余额...",
      mask: true,
    });

    const app = getApp();
    const loginStatus = app.checkLoginStatus();
    const userId = loginStatus.userInfo.id;

    // 计算新的余额
    const currentRechargeBalance = parseFloat(this.data.rechargeBalance);
    const currentGiftBalance = parseFloat(this.data.giftBalance);

    const newRechargeBalance = (currentRechargeBalance + amount).toFixed(2);
    const newGiftBalance = (currentGiftBalance + giftAmount).toFixed(2);

    // 构建更新余额的参数
    const params = {
      userId: userId,
      rechargeBalance: newRechargeBalance,
      giftBalance: newGiftBalance,
    };

    // 调用更新余额接口
    post("/user/update-balance", params)
      .then((res) => {
        wx.hideLoading();
        if (res.code === 200) {
          // 更新本地用户信息
          const userInfo = wx.getStorageSync("userInfo");
          if (userInfo) {
            userInfo.rechargeBalance = newRechargeBalance;
            userInfo.giftBalance = newGiftBalance;
            wx.setStorageSync("userInfo", userInfo);
          }

          // 更新页面显示
          this.setData({
            rechargeBalance: newRechargeBalance,
            giftBalance: newGiftBalance,
            totalBalance: (
              parseFloat(newRechargeBalance) + parseFloat(newGiftBalance)
            ).toFixed(2),
            selectedOption: null,
            customAmount: "",
          });

          // 显示充值成功提示
          wx.showModal({
            title: "充值成功",
            content: `您已成功充值 ¥${amount.toFixed(2)} 元${
              giftAmount > 0 ? `，赠送 ¥${giftAmount.toFixed(2)} 元` : ""
            }`,
            showCancel: false,
          });
        } else {
          console.error("更新余额失败:", res);
          wx.showToast({
            title: "余额更新失败，请联系客服",
            icon: "none",
          });
        }
      })
      .catch((err) => {
        wx.hideLoading();
        console.error("更新余额失败:", err);
        wx.showToast({
          title: "余额更新失败，请联系客服",
          icon: "none",
        });
      });
  },

  // 查看充值历史
  viewRechargeHistory: function () {
    wx.showToast({
      title: "功能开发中",
      icon: "none",
    });
  },

  // 查看消费记录
  viewConsumptionHistory: function () {
    wx.showToast({
      title: "功能开发中",
      icon: "none",
    });
  },
});
